#! /usr/bin/ruby
# manincure.rb version 0.1 

# pineapplecli.manicure.rb version 0.1.2
# *note by cvk_b, explanation of changes
# 1. Remove extraneous info and formatting
# 2. Put Name and commands on a single line, delimited by "QQQ"
# 3. Made sure the x264 options were last on the line    
# 4. Added Autoselect subtitles

$presetMasterList = []
$hashMasterList = []

class PresetClass
  
  @@columnWidth=40
  
  def initialize
    rawPresets = readPresetPlist

    presetStew = []

    presetStew = rawPresets.split("\n")
    presetStew = cleanStew(presetStew)

    presetBreaks = findPresetBreaks(presetStew)

    i = 0
    while i <= presetBreaks.size    
      if i == 0 #first preset
        $presetMasterList[i] = presetStew.slice(0..presetBreaks[i].to_i)
      elsif i < presetBreaks.size #middle presets
        $presetMasterList[i] = presetStew.slice(presetBreaks[i-1].to_i..presetBreaks[i].to_i)
      else #final preset
        $presetMasterList[i] = presetStew.slice(presetBreaks[i-1].to_i..presetStew.length)
      end
      i += 1
    end
    
    buildPresetHash
    displayCommandStrings
  end

  def readPresetPlist # Grab the .plist and store it in presets
    homeLocation = `echo $HOME`.chomp
    inputFile = homeLocation+'/Library/Application\ Support/HandBrake/UserPresets.plist'
    parseCommand = 'cat '+inputFile+' | sed -e \'s/<[a-z]*>//\' -e \'s/<\/[a-z]*>//\'  -e \'/<[?!]/d\' '
    rawPresets = `#{parseCommand}`
  end

  def cleanStew(presetStew) #remove tabbed white space
    presetStew.each do |oneline|
      oneline.strip!
    end
  end

  def findPresetBreaks(presetStew) #figure out where each preset starts and ends
    i = 0
    j = 0
    presetBreaks =[]
    presetStew.each do |presetLine|
      if presetLine =~ /AudioBitRate/
        presetBreaks[j] = i-1
        j += 1
      end
    i += 1
    end
    return presetBreaks
  end

  def buildPresetHash #fill up $hashMasterList with hashes of all key/value pairs
    j = 0
    $presetMasterList.each do |singleServing| #iterate presets
      tempHash = Hash.new
      i = 1
      while i < singleServing.length
        tempHash[singleServing[i]] = singleServing[i+1]
        i += 2
      end
      $hashMasterList[j]=tempHash
      j += 1  
    end   
  end

  def displayCommandStrings    
    $hashMasterList.each do |hash|
      if hash.key?("PresetName")
        generateCLIString(hash)
      end
    end    
  end
  
  def generateCLIString(hash)
    commandString = hash["PresetName"]+"QQQ"
    
    #Video encoder
    if hash["VideoEncoder"] != "FFmpeg"
      commandString << " -e "
      if hash["VideoEncoder"] == "x264 (h.264 Main)"
        commandString << "x264"
      elsif hash["VideoEncoder"] == "x264 (h.264 iPod)"
        commandString << "x264b30"
      else
        commandString << hash["VideoEncoder"].to_s.downcase
      end
    end

    #VideoRateControl
    case hash["VideoQualityType"].to_i
    when 0
      commandString << " -S " << hash["VideoTargetSize"]
    when 1
      commandString << " -b " << hash["VideoAvgBitrate"]
    when 2
      commandString << " -q " << hash["VideoQualitySlider"]
    end

    #FPS
    if hash["VideoFramerate"] != "Same as source"
      commandString << " -r " << hash["VideoFramerate"]
    end
    
    #Audio bitrate
    commandString << " -B " << hash["AudioBitRate"]
    #Audio samplerate
    commandString << " -R " << hash["AudioSampleRate"]
    #Audio encoder
    commandString << " -E "
    case hash["FileCodecs"]
    when /AAC/
      commandString << "faac"
    when /AC-3/
      commandString << "ac3"
    when /Vorbis/
      commandString << "vorbis"
    when /MP3/
      commandString << "lame"
    end
    
    #Container
    commandString << " -f "
    case hash["FileFormat"]
    when /MP4/
      commandString << "mp4"
    when /AVI/
      commandString << "avi"
    when /OGM/
      commandString << "ogm"
    when /MKV/
      commandString << "mkv"
    end
    
    #Cropping
    if !hash["PictureAutoCrop"].to_i
      commandString << " --crop "
      commandString << hash["PictureTopCrop"]
      commandString << ":"
      commandString << hash["PictureBottomCrop"]
      commandString << ":"
      commandString << hash["PictureLeftCrop"]
      commandString << ":"
      commandString << hash["PictureRightCrop"]
    end
    
    #Dimensions
    if hash["PictureWidth"].to_i != 0
      commandString << " -w "
      commandString << hash["PictureWidth"]
    end
    if hash["PictureHeight"].to_i != 0
      commandString << " -l "
      commandString << hash["PictureHeight"]
    end
    
    #Subtitles
    if hash["Subtitles"] != "None"      
      if hash["Subtitles"] != "Autoselect" then
        commandString << " -s "
        commandString << hash["Subtitles"]
      end
    end
    if hash["Subtitles"] == "Autoselect" then commandString << " -U -F" end       
    
    #Booleans
    if hash["ChapterMarkers"].to_i == 1 then commandString << " -m" end
    if hash["PictureDeinterlace"].to_i == 1 then commandString << " -d" end
    if hash["PicturePAR"].to_i == 1 then commandString << " -p" end
    if hash["VideoGrayScale"].to_i == 1 then commandString << " -g" end
    if hash["VideoTwopass"].to_i == 1 then commandString << " -2" end

    #x264 Options
    if hash["x264Option"] != ""
      commandString << " -x "
      commandString << hash["x264Option"]
    end
    
    # That's it, print to screen now
    puts commandString     
  end

end

PresetClass.new
